package com.jia.leetcode2.string;

/**
 * @program: designPattern
 * @description:
 * @author: STU756
 * @create: 2021-03-25 14:02
 */
public class ReverseWordsII {
    /**
     * Reverse words in a string
     * 单词前后没有空格，单词之间有空格
     * @param s
     * @return
     */
    public String reverseWords(String s){
        char[] cs = s.toCharArray();
        for(int i = 0, j = 0; j < cs.length; j++) {
            if(cs[j] == ' ') {
                reverse(cs, i, j - 1);
                i = j + 1;
            }else if(j == cs.length - 1) {
                reverse(cs, i, j);
            }
        }
        return String.valueOf(cs);
    }

    private void reverse(char[] cs, int l, int r) {
        for(int i = l, j = r; i < j; i++, j--) {
            char tmp = cs[i];
            cs[i] = cs[j];
            cs[j] = tmp;
        }
    }

    public static void main(String[] args) {
        String s = "  the  sky is  blue ";
        ReverseWordsII reverseWords = new ReverseWordsII();
        System.out.println(reverseWords.reverseWords(s));
    }
}
